<template>
  <div class="dialog-content">
    <div class="title">
      <span>{{$t( googleVerify ? 'set.close_verofy' : 'set.open_verify')}} </span>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <el-form-item prop="code">
        <el-input v-model="ruleForm.code" :placeholder="$t('login.google_code_input')"></el-input>
      </el-form-item>
      <div class="dialog-footer">
        <el-button type="primary" round @click="submit">{{$t('btn.confirm')}}</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { bindingGoogle, closeGoogle } from '@/api';
import { mapGetters, mapMutations } from 'vuex';

export default {
  data() {
    return {
      ruleForm: {
        code: '',
      },
      rules: {
        code: [{
          required: true,
          message: this.$t('login.google_code_input'),
          trigger: 'change',
        }],
      },
    };
  },
  computed: {
    ...mapGetters(['googleVerify', 'googleCode']),
    toggleApi() {
      return this.googleVerify ? closeGoogle : bindingGoogle;
    },
  },
  methods: {
    ...mapMutations(['SET_GOOGLE_VERIFY']),
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.toggleApi({
            key: this.googleCode,
            code: this.ruleForm.code,
          }).then((res) => {
            if (res.data.status === 1) {
              this.$notify({
                message: this.$t('api.6031'),
                type: 'success',
                duration: 2000,
                showClose: false,
              });
              this.SET_GOOGLE_VERIFY(this.googleVerify ? 0 : 1);
              this.$emit('toggleDialog', { showDialog: false });
            } else {
              this.$message({
                message: this.$t(`api.${res.data.errcode}`),
                type: 'warning',
              });
            }
          }).catch(() => {
            this.$message.error(this.$t('error.catchError'));
          });
        }
      });
    },
  },
};
</script>
